/**
 * Created by jklj077 on 2015/12/22.
 */
var status = require('http-status');
var jwt = require('jsonwebtoken');
var User = require('./models/user');
var options = require('./options');

module.exports = function (app) {
    app.use(function (req, res, next) {
        var token = req.header('token');
        if (token) {
            jwt.verify(token, options.jwtSecret, function (err, decoded) {
                if (err) {
                    return res.status(status.UNAUTHORIZED).json({error: err.message});
                }
                User.findById(decoded.id, function (err, user) {
                    if (user) {
                        req.user = user;
                    }
                    return next();
                });
            });
        } else {
            next();
        }
    });
};
